<template>
  <div class="create-post-page">

    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <Uploader action="/upload" :uploaded="uploadedData" :before-upload="uploadCheck" @file-uploaded="handleFileUploaded"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4">
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.data.url" alt="">
      </template>
    </Uploader>

    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input :rules="titleRules" v-model="titleVal" placeholder="请输入文章标题" type="text" />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <Editor v-model="contentVal" :options="editorOptions" ref="editorRef" @blur="checkEditor"
          :class="{ 'is-invalid': !editorStatus.isValid }">
        </Editor>
        <span v-if="!editorStatus.isValid" class="invalid-feedback mt-1">{{ editorStatus.message }}</span>
        <!-- <validate-input :rules="contentRules" v-model="contentVal" placeholder="请输入文章标题" type="text" tag="textarea">
        </validate-input> -->
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '更新文章' : '发表文章' }}</button>
      </template>
    </validate-form>

  </div>
</template>
<script lang='ts'>

import { defineComponent, ref, onMounted, reactive } from 'vue'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import EasyMDE, { Options } from 'easymde'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '../store'
import Uploader from '@/components/Uploader.vue'
import { beforeUploadCheck } from '../helper'

import CreateMessage from '../components/CreateMessage'
import Editor from '@/components/Editor.vue'
import { usePostStore } from '../store/post'
import { useUserStore } from '../store/user'
interface EditorInstance {
  clear: () => void,
  getMDEInstance: () => EasyMDE | null
}
export default defineComponent({
  name: 'CreatePosts',
  components: {
    ValidateForm,
    ValidateInput,
    Uploader,
    Editor
  },
  setup(props, ctx) {
    const router = useRouter()
    const route = useRoute()
    const postStore = usePostStore()
    const userStore = useUserStore()
    const postId = route.query.id as string
    const uploadedData = ref()
    const textArea = ref<null | HTMLTextAreaElement>(null)
    const editorRef = ref<null | EditorInstance>()
    const editorOptions: Options = {
      spellChecker: false
    }
    const editorStatus = reactive({
      isValid: true,
      message: ''
    })
    const checkEditor = () => {
      if (contentVal.value.trim() === '') {
        editorStatus.isValid = false// 不合法
        editorStatus.message = '文章详情内容不能为空'
      } else {
        editorStatus.isValid = true// 不法
        editorStatus.message = ''
      }
    }

    const store = useStore<GlobalDataProps>()
    const isEditMode = !!route.query.id// 把isEditMode转变成boolean类型
    const titleVal = ref('')
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    let ImageId = ''
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        ImageId = rawData.data._id
      }
    }
    const onFormSubmit = async (result: boolean) => {
      checkEditor()
      if (result && editorStatus.isValid && userStore.data) {
        const { column, _id } = userStore.data
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id
          }
          if (ImageId) {
            newPost.image = ImageId
          }

          // const actionName = isEditMode ? 'updatePost' : 'createPost'
          // // 'updatePosts' : 'createPosts'，
          // const sendData = isEditMode
          //   ? {
          //     id: route.query.id,
          //     payload: newPost
          //   }
          //   : newPost
          // // 有id就是编辑，没有就是新建
          // store.dispatch(actionName, sendData).then(() => {
          //   CreateMessage('发表成功，2s后跳转到文章', 'success', 2000)
          //   setTimeout(() => {
          //     router.push({
          //       name: 'column',
          //       params: {
          //         id: column
          //       }
          //     })
          //   }, 2000)
          // })
          if (isEditMode) {
            await postStore.updatePost(postId, newPost)
          } else {
            await postStore.createPost(newPost)
          }
          CreateMessage('发表成功，2秒后跳转到文章', 'success', 2000)
          setTimeout(() => {
            router.push({ name: 'column', params: { id: column } })
          }, 2000)
        }
      }
    }

    // 从自组件传递过来的校验之前的规则
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
      const { passed, error } = result
      if (error === 'format') {
        CreateMessage('上传图片只能是JPEGs/PNG格式', 'error', 2000)
      }
      if (error === 'size') {
        CreateMessage('上传图片大小不能超过 1MB', 'error', 2000)
      }
      return passed
    }
    // onMounted(() => {
    //   if (isEditMode) {
    //     store.dispatch('fetchPosts', route.query.id).then((rawData: ResponseType<PostProps>) => {
    //       const currentPost = rawData.data
    //       if (currentPost.image) {
    //         console.log(currentPost.image, 'currentPost.image12')
    //         uploadedData.value = 'http://typescript-vue.oss-cn-beijing.aliyuncs.com/vue-marker/6094907eb558154f0392cd07.jpg'
    //       } else {
    //         uploadedData.value = {
    //           data: {
    //             url: 'http://typescript-vue.oss-cn-beijing.aliyuncs.com/vue-marker/6094907eb558154f0392cd07.jpg'
    //           }
    //         }
    //       }

    //       titleVal.value = currentPost.title
    //       contentVal.value = currentPost.content || ''
    //     })
    //   }
    // })
    // onMounted(() => {
    //   if (editorRef.value) {
    //     console.log(editorRef.value.getMDEInstance(), '  editorRef.value.getMDEInstance()')
    //   }
    //   if (isEditMode) {
    //     postStore.fetchPost(postId).then((currentPost: any) => {
    //       // const currentPost = rawData.data

    //       if (currentPost.image) {
    //         uploadedData.value = { data: currentPost.image }
    //       }
    //       titleVal.value = currentPost.title
    //       contentVal.value = currentPost.content || ''
    //     })
    //   }
    // })
    onMounted(() => {
      if (isEditMode) {
        postStore.fetchPost(postId).then((currentPost) => {
          console.log(currentPost,
            currentPost)

          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })
    return {
      titleVal,
      contentVal,
      titleRules,
      contentRules,
      onFormSubmit,
      uploadCheck,
      handleFileUploaded,
      uploadedData,
      isEditMode,
      textArea,
      editorOptions,
      editorRef,
      checkEditor,
      editorStatus

    }
  }
})
</script>
<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploaded-area {
  position: relative;
}

.uploaded-area:hover h3 {
  display: block;
}

.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
